package com.bamboowind.producer.routing;

import com.bamboowind.producer.util.RabbitMqUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;

/**
 * 路由模式：生产者
 *
 * @author cpw
 */
public class ProducerRouting {
    private final static String QUEUE_NAME1 = "rabbitmq-directQueue1";
    private final static String QUEUE_NAME2 = "rabbitmq-directQueue2";
    private final static String EXCHANGE_NAME = "rabbitmq-directExchange";

    public static void main(String[] args) throws IOException {

        //3.创建连接Connection
        Connection connection = RabbitMqUtils.getConnection();

        //4.创建Channel
        Channel channel = connection.createChannel();


        /**
         * exchangeDeclare(String exchange, BuiltinExchangeType type, boolean durable, boolean autoDelete, boolean internal, Map<String, Object> arguments)
         * 参数:
         *      1.exchange:交换机名称
         *      2.type:交换机类型
         *            DIRECT("direct"), 定向
         *            FANOUT("fanout"), 广播，发送消息到每一个与之绑定的队列
         *            TOPIC("topic"),   通配符的方式
         *            HEADERS("headers");参数匹配
         *      3.durable:是否持久化
         *      4.autoDelete:自动删除
         *      5.internal:内部使用，一般false
         *      6.arguments:参数
         * */

        //5.创建交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT, true, false, false, null);

        //6.创建队列
        channel.queueDeclare(QUEUE_NAME1, true, false, false, null);
        channel.queueDeclare(QUEUE_NAME2, true, false, false, null);

        /**
         * queueBind(String queue, String exchange, String routingKey, Map<String)
         * 参数:
         *      1.queue:队列名称
         *      2.exchange:交换机名称
         *      3.routingKey:路由键绑定规则
         *          如果交换机的类型为fanout，那么routingKey设置为""
         * */

        //7.绑定队列和交换机

        //队列1的绑定，绑定的是error的路由key(存储到数据库)
        channel.queueBind(QUEUE_NAME1, EXCHANGE_NAME, "error");
        //队列2的绑定，绑定的是info,error,warning的路由key(打印到控制台)
        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "info");
        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "error");
        channel.queueBind(QUEUE_NAME2, EXCHANGE_NAME, "warning");
        //8.发送消息
//        String body = "cpw发送了一条信息，日志级别为info...";
        String body = "cpw发送了一条信息，日志级别为error...";
        channel.basicPublish(EXCHANGE_NAME, "error", null, body.getBytes());

        //9.释放资源
        RabbitMqUtils.closeConnectionAndChannel(connection, channel);
    }
}
